package com.qdsgjsfk.vision.util;


import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UtilString {
    /**
     * is null or its length is 0 or it is made by space
     * <p>
     * <pre>
     * isBlank(null) = true;
     * isBlank(&quot;&quot;) = true;
     * isBlank(&quot;  &quot;) = true;
     * isBlank(&quot;a&quot;) = false;
     * isBlank(&quot;a &quot;) = false;
     * isBlank(&quot; a&quot;) = false;
     * isBlank(&quot;a b&quot;) = false;
     * </pre>
     *
     * @param str
     * @return if string is null or its size is 0 or it is made by space, return
     * true, else return false.
     */
    public static boolean isBlank(String str) {
        return (str == null || str.trim().length() == 0);
    }

    /**
     * is null or its length is 0
     *
     * @param str
     * @return if string is null or its size is 0, return true, else return
     * false.
     */
    public static boolean isEmpty(String str) {
        return (str == null || str.length() == 0 || "null".equals( str ));
    }


    public static String nullStrToEmpty(String str) {
        return (str == null ? "" : str);
    }


    public static String capitalizeFirstLetter(String str) {
        if (isEmpty( str )) {
            return str;
        }

        char c = str.charAt( 0 );
        return (!Character.isLetter( c ) || Character.isUpperCase( c )) ? str : new StringBuilder( str.length() ).append( Character.toUpperCase( c ) )
                .append( str.substring( 1 ) )
                .toString();
    }

    /**
     * encoded in utf-8
     * <p>
     * <pre>
     * utf8Encode(null)        =   null
     * utf8Encode("")          =   "";
     * utf8Encode("aa")        =   "aa";
     * utf8Encode("啊啊啊啊")   = "%E5%95%8A%E5%95%8A%E5%95%8A%E5%95%8A";
     * </pre>
     *
     * @param str
     * @return
     * @throws UnsupportedEncodingException if an error occurs
     */
    public static String utf8Encode(String str) {
        if (!isEmpty( str ) && str.getBytes().length != str.length()) {
            try {
                return URLEncoder.encode( str, "UTF-8" );
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException( "UnsupportedEncodingException occurred. ", e );
            }
        }
        return str;
    }

    /**
     * encoded in utf-8, if exception, return defultReturn
     *
     * @param str
     * @param defultReturn
     * @return
     */
    public static String utf8Encode(String str, String defultReturn) {
        if (!isEmpty( str ) && str.getBytes().length != str.length()) {
            try {
                return URLEncoder.encode( str, "UTF-8" );
            } catch (UnsupportedEncodingException e) {
                return defultReturn;
            }
        }
        return str;
    }

    /**
     * get innerHtml from href
     * </pre>
     * </ul>
     */
    public static String getHrefInnerHtml(String href) {
        if (isEmpty( href )) {
            return "";
        }

        String hrefReg = ".*<[\\s]*a[\\s]*.*>(.+?)<[\\s]*/a[\\s]*>.*";
        Pattern hrefPattern = Pattern.compile( hrefReg, Pattern.CASE_INSENSITIVE );
        Matcher hrefMatcher = hrefPattern.matcher( href );
        if (hrefMatcher.matches()) {
            return hrefMatcher.group( 1 );
        }
        return href;
    }

    /**
     * 处理HTML特殊字符
     * process special char in html
     * <p>
     * <pre>
     * htmlEscapeCharsToString(null) = null;
     * htmlEscapeCharsToString("") = "";
     * htmlEscapeCharsToString("mp3") = "mp3";
     * htmlEscapeCharsToString("mp3&lt;") = "mp3<";
     * htmlEscapeCharsToString("mp3&gt;") = "mp3\>";
     * htmlEscapeCharsToString("mp3&amp;mp4") = "mp3&mp4";
     * htmlEscapeCharsToString("mp3&quot;mp4") = "mp3\"mp4";
     * htmlEscapeCharsToString("mp3&lt;&gt;&amp;&quot;mp4") = "mp3\<\>&\"mp4";
     * </pre>
     *
     * @param source
     * @return
     */
    public static String htmlEscapeCharsToString(String source) {
        return UtilString.isEmpty( source ) ? source : source.replaceAll( "&lt;", "<" )
                .replaceAll( "&gt;", ">" )
                .replaceAll( "&amp;", "&" )
                .replaceAll( "&quot;", "\"" );
    }

    /**
     * 转半角为全角 transform half width char to full width char
     * <p>
     * <pre>
     * fullWidthToHalfWidth(null) = null;
     * fullWidthToHalfWidth("") = "";
     * fullWidthToHalfWidth(new String(new char[] {12288})) = " ";
     * fullWidthToHalfWidth("！＂＃＄％＆) = "!\"#$%&";
     * </pre>
     *
     * @param s
     * @return
     */
    public static String fullWidthToHalfWidth(String s) {
        if (isEmpty( s )) {
            return s;
        }

        char[] source = s.toCharArray();
        for (int i = 0; i < source.length; i++) {
            if (source[i] == 12288) {
                source[i] = ' ';
                // } else if (source[i] == 12290) {
                // source[i] = '.';
            } else if (source[i] >= 65281 && source[i] <= 65374) {
                source[i] = (char) (source[i] - 65248);
            } else {
                source[i] = source[i];
            }
        }
        return new String( source );
    }

    /**
     * 去掉手机号内除数字外的所有字符
     *
     * @param phoneNum 手机号
     * @return
     */
    public static String formatPhoneNum(String phoneNum) {
        String regex = "(\\+86)|[^0-9]";
        Pattern pattern = Pattern.compile( regex );
        Matcher matcher = pattern.matcher( phoneNum );
        return matcher.replaceAll( "" );
    }

    //手机号正则
    public static boolean isPhoneNumNo(String phoneNum) {
        String regExp = "^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(14[5-9]))\\d{8}$";
        Pattern pPhone = Pattern.compile( regExp );
        return pPhone.matcher( phoneNum ).matches();
    }

    //身份证正则
    public static boolean isIdCardNumNo(String idCardNum) {
        Pattern idcard = Pattern.compile( "^[0-9]{15}$|^[0-9]{17}[0-9xX]$" );
        return idcard.matcher( idCardNum ).matches();
    }

    //密码正则
    public static boolean isPasswordNo(String password) {
        Pattern mPassword = Pattern.compile( "^(?![a-zA-Z]+$)(?![0-9]+$)(?![.]+$)(?![_]+$)[a-zA-Z0-9._]+$" );
        return mPassword.matcher( password ).matches();
    }

    public static String formatPhone(String phoneNum) {
        String phoneNumFormat = "";
        StringBuilder sb = new StringBuilder( phoneNumFormat );
        String substring = phoneNum.substring( 0, 3 );
        sb.append( substring + " " );
        String substring1 = phoneNum.substring( 3, 7 );
        sb.append( substring1 + " " );
        String substring2 = phoneNum.substring( 7, 11 );
        sb.append( substring2 );
        return sb.toString();
    }

    /**
     * String转换成double 保留N位小数。
     *
     * @param a
     * @return
     */
    public static double stringToDouble(String a) {
        double b = Double.valueOf( a );
        DecimalFormat df = new DecimalFormat( "#.00" );//此为保留1位小数，若想保留2位小数，则填写#.00  ，以此类推
        String temp = df.format( b );
        b = Double.valueOf( temp );
        return b;
    }

    /**
     * 字符类型转换成整数类型
     *
     * @param str
     * @return
     */
    public static Integer intValueOf(String str) {
        Integer value = 0;
        try {
            value = Integer.valueOf( str );
        } catch (NumberFormatException e) {
        }
        return value;
    }

    /**
     * 字符串转换成长整型
     *
     * @param str
     * @return
     */
    public static Long longValueOf(String str) {
        Long value = 0l;
        try {
            value = Long.valueOf( str );
        } catch (NumberFormatException e) {
        }
        return value;
    }

    /// <summary>
    /// 判断字符串中是否包含中文
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static boolean IsContainChinese(String str) {
        boolean bflag = false;
        if (str == null) {
            return bflag;
        }
        char[] c = str.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] >= 0x4E00 && c[i] <= 0x29FA5) {
                bflag = true;
                return bflag;// 有一个中文字符就返回
            }
        }
        return bflag;
    }

    // 数组转string
    public static String listToString(List<String> list_message_ID) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < list_message_ID.size(); i++) {
            buffer.append( list_message_ID.get( i ) );
            if (i < list_message_ID.size() - 1) {
                buffer.append( "," );
            }
        }
        return buffer.toString();
    }

    /**
     * 提供精确的加法运算
     *
     * @param v1 被加数
     * @param v2 加数
     * @return 两个参数的和
     */
    public static double add(double v1, double v2) {
        BigDecimal b1 = new BigDecimal( Double.toString( v1 ) );
        BigDecimal b2 = new BigDecimal( Double.toString( v2 ) );
        return b1.add( b2 ).doubleValue();
    }

    /**
     * 提供精确的减法运算
     *
     * @param v1 被减数
     * @param v2 减数
     * @return 两个参数的差
     */
    public static double sub(double v1, double v2) {
        BigDecimal b1 = new BigDecimal( Double.toString( v1 ) );
        BigDecimal b2 = new BigDecimal( Double.toString( v2 ) );
        return b1.subtract( b2 ).doubleValue();
    }

    /**
     * 提供精确的乘法运算
     *
     * @param v1 被乘数
     * @param v2 乘数
     * @return 两个参数的积
     */
    public static double mul(double v1, double v2) {
        BigDecimal b1 = new BigDecimal( Double.toString( v1 ) );
        BigDecimal b2 = new BigDecimal( Double.toString( v2 ) );
        return b1.multiply( b2 ).doubleValue();
    }

    /**
     * @return data1 与 data2拼接的结果
     */

    public static byte[] addBytes(byte[] data1, byte[] data2) {

        byte[] data3 = new byte[data1.length + data2.length];

        System.arraycopy( data1, 0, data3, 0, data1.length );

        System.arraycopy( data2, 0, data3, data1.length, data2.length );

        return data3;

    }


}

